//app.js
App({
  onLaunch: function () {

    //获取设备信息
    this.getSystemInfo();

    // 登录
    var self = this;
    var host = this.globalData.host

    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.login({
      success: function(res) {
        var params = {
          code: res.code,
          appId: self.globalData.appId
        }
        wx.request({
          url: host + '/yq/auth',
          data: params,
          success: function (res) {
            wx.hideLoading();
            console.log(res);
            var userInfo = res.data.info.user;
            var unionId = res.data.info.unionId;
            var openId = res.data.info.openId;
            var token = res.data.info.token;
            wx.setStorageSync("openId", openId);
            wx.setStorageSync("token", token);
            self.globalData.userInfo = userInfo;

            // 获取用户位置信息
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                wx.getLocation({
                  type:'gcj02',
                  success: function (res) {
                    console.log(res);
                    var url = host + '/yq/user/updateLocation';
                    var params = {
                      latitude: res.latitude,
                      longitude: res.longitude
                    }
                    self.request(url, params);
                  }
                })
              },
              fail(res) {
                console.log("userLocation authorize fail");
                console.log(res);
                wx.hideLoading();
                wx.showModal({
                  title: '提示',
                  content: '没有获取位置信息的权限',
                  confirmText: '去设置',
                  success(res) {
                    if (res.confirm) {
                      wx.openSetting({
                      })
                    }
                  }
                })
              }
            })

            if (self.wechatLoginCallback) {
              self.wechatLoginCallback();
            }
          },
          fail: function (err) {
            wx.hideLoading();
          }
        })
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) { },
    })
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
        
    //   }
    // })
    // 获取用户信息
    // wx.getSetting({
    //   success: res => {
    //     if (res.authSetting['scope.userInfo']) {
    //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
    //       wx.getUserInfo({
    //         success: res => {
    //           // 可以将 res 发送给后台解码出 unionId
    //           this.globalData.userInfo = res.userInfo

    //           // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    //           // 所以此处加入 callback 以防止这种情况
    //           if (this.userInfoReadyCallback) {
    //             this.userInfoReadyCallback(res)
    //           }
    //         }
    //       })
    //     }
    //   }
    // })
  },
  onShow: function () {
    //隐藏系统tabbar
    wx.hideTabBar();
  },



  //给tabBar.list配置中的页面使用
  editTabbar: function () {
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },

  //获取设备信息，看是不是iPhone X 以上的设备，控制底下多留点空间
  getSystemInfo: function () {
    let t = this;
    wx.getSystemInfo({
      success: function (res) {
        t.globalData.navHeight = res.statusBarHeight + 46;

        const equipment = res.model;
        const equipmentList = t.globalData.equipmentList
        for (let item of equipmentList) {
          if (equipment.indexOf(item) != -1) {
            t.globalData.isIphoneX = true;
          }
        }
        
      }
    });
  },

  globalData: {
    // appId: 'v3RaWZzX',
    appId: 'DoeqKYNP',
    //客户端设备信息,是否是iPhone X以上的苹果手机
    isIphoneX: false,
    equipmentList: [
      "iPhone X",
      "iPhone XS Max",
      "iPhone XS",
      "iPhone XR"
    ],
    userInfo: null,
    navHeight: null,
    themeColor: '#000', // 主题色
    // host: 'http://192.168.50.19:9090',
    // host: 'http://192.168.50.18:9090',
    host: 'https://release.zhen-yee.com',
    currentVer: 'v1.3.2',
    shopUser: null,
    aesKey: 'youqu!@#$%^&*()-',
    isTimeout: true,
    utils: require("utils/util.js"),

    //加入自定义tabbar的参数
    tabBar: {
      "list": [
        {
          "pagePath": "/pages/calendar/calendar",
          "text": "日历",
          "iconPath": "/resources/pictures/tabbar/calendar.png",
          "selectedIconPath": "/resources/pictures/tabbar/calendar.png"
        },
        {
          "pagePath": "/pages/favorite/favorite",
          "text": "卡包",
          "iconPath": "/resources/pictures/tabbar/favorite.png",
          "selectedIconPath": "/resources/pictures/tabbar/favorite.png"
        },
        {
          "pagePath": "/pages/index/index",
          "text": "",
          "iconPath": "/resources/pictures/tabbar/home.png",
          "selectedIconPath": "/resources/pictures/tabbar/home.png"
        },
        {
          "pagePath": "/pages/store/store",
          "text": "商城",
          "iconPath": "/resources/pictures/tabbar/store.png",
          "selectedIconPath": "/resources/pictures/tabbar/store.png"
        },
        {
          "pagePath": "/pages/user/user",
          "text": "我的",
          "iconPath": "/resources/pictures/tabbar/user.png",
          "selectedIconPath": "/resources/pictures/tabbar/user.png"
        }
      ],
      "color": "#888",
      "selectedColor": "#e0342e",
      "backgroundColor": "#fff"
    }
  },


  request: function (url, params, success, fail, compl) {
    if (params == null) {
      params = {};
    }
    var timestamp = String(this.globalData.utils.accDiv(new Date().getTime(), 1000));
    if (timestamp.indexOf(".") >= 0) {
      timestamp = timestamp.split(".")[0];
    }
    params.appId = this.globalData.appId;
    params['openId'] = wx.getStorageSync("openId");
    params.timestamp = timestamp;
    params.sign = this.globalData.utils.genSign(params);
    wx.request({
      url: url,
      data: params,
      success: function (res) {
        if (res.data.status == 200) {
          if (success) {
            success(res.data);
          }
        } else {
          if (fail) {
            fail(res.data);
          }
          wx.showToast({
            title: String(res.data.msg),
            icon: 'none'
          })
        }
      },
      fail: function () {
        if (fail) {
          fail(null);
        }
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      },
      complete: function () {
        if (compl) {
          compl();
        }
      }
    })
  },
  requestLoading: function (url, params, success, fail, complete) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    var s = function (res) {
      wx.hideLoading();
      if (success) {
        success(res);
      }
    };
    var f = function (res) {
      wx.hideLoading();
      if (fail) {
        fail(res);
      }
    };
    var c = function () {
      if (complete) {
        complete();
      }
    };
    this.request(url, params, s, f, c);
  }
})